package com.axdac.mixbind.sql.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;


import com.axdac.mixbind.sql.adapter.AndroidDBAdapter;
import com.axdac.mixbind.sql.adapter.IDBAdapter;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.List;


public class DBInvo implements InvocationHandler{
	private SQLiteDatabase.CursorFactory factory=null;
	private IDBAdapter Adapter;
	private String DBname;
	private String version;
	private String CursorFactory;
	private String tableList;

	public DBInvo(Context context,String DBname, String version, String cursorFactory, String tableList) {
		this.DBname = DBname;
		this.version = version;
		CursorFactory = cursorFactory;
		this.tableList = tableList;

		if (!CursorFactory.equals("")){
			try {
				factory = (SQLiteDatabase.CursorFactory) Class.forName(CursorFactory).newInstance();
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
		Object table = null;
		try {
			table = Class.forName(tableList).newInstance();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		try {
			Adapter = new AndroidDBAdapter(context,DBname,factory,Integer.parseInt(version),table);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		// TODO Auto-generated method stub
		String sqlstr = null;
		if(method.isAnnotationPresent(SQL.class)) {
			SQL sql = method.getAnnotation(SQL.class);
			sqlstr = sql.value();
		}else {
			return null;
		}
		System.out.println("DBInvo:has:"+sqlstr);
		if(args!=null) {
			for (int i = args.length-1; i >=0; i--) {
				String target = "@" + (i + 1);
				String replace = "'" + args[i].toString() + "'";
				sqlstr = sqlstr.replace(target,replace );
			}
		}
		System.out.println("DBInvo:after-param:"+sqlstr);
		
		if(method.isAnnotationPresent(Entity.class)) {
			Entity entity = method.getAnnotation(Entity.class);
			System.out.println("DBInvo:entity:"+entity.value());
			List<Object> list = Adapter.execSql(sqlstr, entity.value());
			return list;
		}
		
		return Adapter.execSql(sqlstr);
	}

	
}
